import { getInfoProfile, getUserDetailById, login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

import { Message } from 'element-ui'
import { resetRouter } from '@/router/index'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    updataToken(state, token) {
      state.token = token
      // 将token保存到本地存储
      setToken(token)
    },
    // 定义删除token的函数
    delToken(state) {
      state.token = ''
      removeToken()
    },
    updataUserInfo(state, info) {
      state.userInfo = info
    },
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async initToken(context, formData) {
      // 发送请求
      const res = await login(formData)
      // 3.判断用户是否登录成功
      if (res.code !== 10000) return Message.error(res.message)
      Message.success(res.message)
      // 保存token到vuex中
      context.commit('updataToken', res.data)
    },
    async setUserInfo(context) {
      try {
        const res = await getInfoProfile()
        console.log(res, 'getInfoProfile')
        const info = await getUserDetailById(res.data.userId)
        // console.log(info, 'info')
        context.commit('updataUserInfo', { ...res.data, ...info.data })
        return res.data.roles.menus
      } catch (error) {
        console.log(error)
      }
    },
    logout(context) {
      // 删除vuex的用户信息
      context.commit('delUserInfo')
      // 删除vuex的token
      context.commit('delToken')
      // 重置路由
      resetRouter()
    }
  }

}
